/**
 * @author klv
 */
var watchlist_core = function(container,config,callback){
    this.config=config;   // currentId is saved in this object.
    //{currentId:***,type:****}
    this.container=container;
    this.callback=callback;
    this.tickerList=null;
    this.init();
};
watchlist_core.prototype={
    init:function(){
        this.tickerList=new QS_tickerList(this.container,this.config,this.callback);
    },
	setID:function(id){
		this.id=id;
	},
    getCurrentConfig:function(){
        return this.config;
    },
	setTickerValidation:function(tickerValidation){
		this.tickerList.tValidation = tickerValidation;
	},
    empty:function(){
        this.tickerList.empty();
    },
    getCurrentId:function(){  // get the oepned watchlist id or portfolio id.
        return this.config.currentId;  
    },
    openWatchlist:function(id,name,callback){
        var self = this;
        //this.tabmenu.setDisable();
        this.tickerList.show(); // show grid.
        if (this.config.currentId != id) {
            QS_watchlistDataManager.unregisterWatchlist(this, this.config.currentId);
            QS_watchlistDataManager.registerWatchlist(this, id);
        }
        this.config.currentId = id;
        QS_watchlistDataManager.getHoldings(id, function(holdings,wid){
            if(self.config.currentId == wid){  
                self.config.type = QS_watchlistDataManager.getTypeById(id)
                self.tickerList.setWatchlistId(id);
				if (self.config.isLPLUser) {
					self.tickerList.setColumnsByKeys(self._LPLCustomizeColum(id));
				}
				if(holdings!=null&&(holdings.length==0||$.isPlainObject(holdings[0]))){
					self.tickerList.reBindData(holdings);
				}else{
					self.addTickers(holdings,true);
				}
                if(typeof callback=='function'){ 
                    callback(id,self.config.type);
                }
            }     
        });
    },
	_LPLCustomizeColum: function(id, dataCols){
		var dataCols=this.tickerList.getColumnsView();
        var sourceType = QS_watchlistDataManager.getSourceById(id);
        //insert account/household into default column
        for (var i = 0; i < dataCols.length; i++) {
            if (dataCols[i].dataIndex == 'Household' || dataCols[i].dataIndex == 'AccountName') {
                dataCols.splice(i, 1);
                i--;
            }
        }
        if (sourceType == 'LPLP') {
            dataCols.push({
                dataIndex: 'AccountName',
                width: 80
            });
            dataCols.push({
                dataIndex: 'Household',
                width: 70
            });
        }
        else 
            if (sourceType == 'LPLH') {
                dataCols.push({
                    dataIndex: 'AccountName',
                    width: 80
                });
            }
        return dataCols;
    },
    reNameWatchlist:function(id,type,callback){
         Util.prompt(QS_Lang.text["watchlistinput"], function(name){
                var name = $.trim(name);
                QS_watchlistDataManager.renameWatchlist(name,id, type,function(){
                    if(typeof callback=='function'){
                        callback(name);
                    }
                    Util.message(QS_Lang.text["watchlistrenamesuccess"]);
                });
            },{
                validateMethod:this._validateNameMethod
            }
        );
    },
    createWatchlist:function(name,type,holdings,callback){
        var self = this;
        QS_watchlistDataManager.createWatchList(name, type, holdings||[], function(data){
            if(typeof(data.portfolioId)!="undefined"&&data.portfolioId!= -1){  // creat success  //&&data.holdings&&data.holdings.length
				Util.message(QS_Lang.text["watchlistcreatesuccess"]);
				if (typeof callback=='function') {
					callback({id:data.portfolioId,name:name,type:type}); // data = {portfolioId: id,holdings:holdings,ret:error coed};
				}
            }else{
				Util.message(QS_Lang.text["watchlistcreateerror"]);
				if (typeof callback=='function') {
					callback(null); // data = {portfolioId: id,holdings:holdings,ret:error coed};
				}
			}
        });
    },
    saveAsWatchlist:function(copyFromId,callback){
        var self=this;
        Util.prompt(QS_Lang.text["watchlistinput"], function(name){
                    var name = $.trim(name);
                    QS_watchlistDataManager.saveAsWatchlist(name,copyFromId,function(data){
                        var id = data.portfolioId;
                        if (data.ret&&data.ret!=-1) {
                            Util.message(QS_Lang.text["watchlistcreateerror"]);
                        }else {
                            self.openWatchlist(id,name,function(wsid,type){
                                if (typeof(callback)=="function") {
                                    callback(id,name,type);
                                }
                            });
                            Util.message(QS_Lang.text["watchlistsaveassuccess"]);
                        }
                    });
            },{
                validateMethod:this._validateNameMethod
            }
        );
         
    },
    saveWatchlist:function(id,callback){
        QS_watchlistDataManager.saveHoldings(id, function(d){  // update and sync holdings with other watchlist in WatchlistDataManager.
            //DBHelper.updatePortfolio(id, $.toJSON(getUpdateHoldingList(id)), function(d){
            var msg = '';
            if (d.ret == '') {
                msg = QS_Lang.text["watchlistsaveerror"];
            }
            else if (d.ret == '-4') {
                msg = QS_Lang.text["watchlistsaveerror2"];
            }
            else if (d.ret < 0) {
                msg = QS_Lang.text["watchlistsaveerror"];
            }else {
                msg = QS_Lang.text["watchlistsavedsuccessfully"];
            }
            if (msg != '') {
                Util.message(msg);
            }
            if (typeof callback=='function') {
                callback(id);
            }
        });
    },
    deleteWatchlist:function(id, callback){
        if (QS_watchlistDataManager.getPermissionById(id) == 0) {  // MStar watchlist template can't be deleted.
            if(QS_watchlistDataManager.getSourceById(id)=="screener"){
                Util.message(QS_Lang.watchlist["watchlistdeletescreenerprompt"]);
            }else{
                Util.message(QS_Lang.text["watchlistcannotdelete"]);
            }
            return;
        }
        var self = this;
        Util.confirm(QS_Lang.text["watchlistdelconfirm"].replace('[TITLE]', this.getWatchlistName(id)), function(b){
            if (!b) {
                return;
            }
            with({id: id}){
                QS_watchlistDataManager.deleteWatchlist(id, function(d){
                    if (d != null&& d.op && d.portfolioId == id) {
                        if (callback && typeof callback == 'function') {
                            callback(d);
                            Util.message(QS_Lang.text["watchlistdeletesuccess"]);
                        }
                    }else{
                        if (callback && typeof callback == 'function') {
                            callback(d);
                            Util.message(QS_Lang.text["watchlistdeleteerror"]);
                        }
                    }
                });
            }
        })
    },
	//interface for Watchlist DataManager
    onWatchlistDataDelete: function(portfolioId){
        QS_watchlistDataManager.unregisterWatchlist(this, portfolioId);
		if(this.callback.afterDeleteWatchlist){
			this.callback.afterDeleteWatchlist(portfolioId);
		}
    },
    onWatchlistRename:function(wid,name){
        if(this.callback.afterRenameWatchlist){
            this.callback.afterRenameWatchlist(wid,name);
        }
    },
	//when the watchlist window is open the updated watchlist.
    refreshHoldings: function(portfolioId, holdings){
        if (portfolioId == this.config.currentId) { 
            if(this.callback.afterSaveHoldings){
				this.callback.afterSaveHoldings(portfolioId, holdings);
			}
			this.tickerList.reBindData(holdings);
        }
    },
    getWatchlistName: function(id){
        if (id == 0) {
            return QS_Lang.watchlist["startupname"];
        }
        else {
            return QS_watchlistDataManager.getNameById(id);
        }
        return '';
    },
    _validateNameMethod: function(title){
        title = $.trim(title);
        if (!title || title.length < 1) {
            Util.message(QS_Lang.text["watchlistinput"]);
            return false;
        }
        if (!QS_Validator.test(title, 'name')) {
            return false;
        }
        if (title.length > self._maxTitleLength) {
            Util.message(QS_Lang.text["watchlisttitle"]);
            return false;
        }
        if (title == 'Untitled') {
            return false;
        }
        if (QS_watchlistDataManager.checkWatchlistName(title) !== false) {
            Util.message(QS_Lang.text["watchlisttitle2"]);
            return false;
        }
        return true;
    },
    changeOutSize:function(w,h){
        this.tickerList.changeOutSize(w,h);
    },
    updateData:function(gKey,needupdatefiled){
        this.tickerList.updateData(gKey,needupdatefiled);
    },
    sort:function(dataIndex,direction){
        this.tickerList.sort(dataIndex,direction);
    },
    groupBy:function(dataIndex,callback){
        this.tickerList.groupBy(dataIndex,callback);
    },
    changeViewType:function(viewType){//list,listwrap,listgroup,list wrap&group,heatmap
        this.tickerList.changeViewType(viewType);
    },
    addTickers:function(tickers,showAlert){
        this.tickerList.addTickers(tickers,showAlert)
    },
    removeTicker:function(holdingId, gkey){
        this.tickerList.removeTicker(holdingId, gkey);
    },
    deleteColumns:function(dataIndex){
        this.tickerList.deleteColumns(dataIndex);
    },
    getSortColumns:function(){
        return this.tickerList.getSortColumns();
    },
    getGroupBy:function(){
        return this.tickerList.config.groupBy;
    },
    getlastSortCellKey:function(){  // get the sort field
        return this.tickerList.getlastSortCellKey();
    },
    getSortOrder:function(){
        return this.tickerList.getSortOrder();  
    },
    getViewKeys:function(){
        return this.tickerList.config.viewKey;
    },
	getIDs:function(){
		return this.tickerList.getIDs();
	},
    setColumns:function(cols){
        this.tickerList.setColumns([].concat(cols));
    },
    setColumnsByKeys:function(cols){
        this.tickerList.setColumnsByKeys([].concat(cols));
    },
    getDisplayLayout:function(){
        return this.tickerList.config.displayLayout
    },
    setDisplayLayout:function(ty){
        this.tickerList.config.displayLayout = ty;
    },
    getColumnCfg:function(){
        return this.tickerList.getColumnCfg();
    },
    hide:function(){
        this.tickerList.hide();
    },
    show:function(){
        this.tickerList.show();
    },
    removeRow:function(rowid){
        this.tickerList.removeRow(rowid);
    },
    stopSubscribe:function(){
        this.tickerList.stopSubscribe();
    },
    saveConfig:function(){
        
    },
    clear:function(){
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
    saveConfig:function(){
        
    }
}
